//
//  CYOAuthViewController.swift
//  CYSinaWB
//
//  Created by mac on 16/2/17.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class CYOAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func testAccount() {
        let jsString = "document.getElementById('userId').value = 'www.237355306@qq.com',document.getElementById('passwd').value = 'chen13294817140' "
        //字符串对象执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "justTest", style: .Plain, target: self, action: "testAccount")
        
        //加载授权页面
        loadOauthPage()
    }
    
    //页面消失时dismiss
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    private func loadOauthPage() {
//        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=527206556&redirect_uri=http://baidu.com"
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)!
        
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
}

extension CYOAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //获取成功后的授权码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        if urlString.containsString("code") {
            //截取
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(urlString,query,code)
            //code 换取令牌
//            loadAccessToken(code)
            CYAccountViewModel.sharedViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
//            CYAccountViewModel().loadAccessToken(code, finished: { (isSuccess) -> () in
            
                if isSuccess {
                    self.dismissViewControllerAnimated(true, completion: nil)
//                    UIApplication.sharedApplication().keyWindow?.rootViewController = CYWelcomeController()
                    NSNotificationCenter.defaultCenter().postNotificationName(KChooseRootVC, object: nil)
                } else {
                    SVProgressHUD.showErrorWithStatus("登录失败,请检查您的网络是否正常")
                }
            })
            return false
        }
        return true
    }
    //加载用户的token
   }
